package com.example.kx031;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.Toast;

/**
 * 进度条 开心消消乐
 */
public class MainActivity extends AppCompatActivity {

    private ProgressBar progressBar;

    int mProgress = 0;

    Handler handler; //线程共享,在子线程中  handler.sendMessage(m); 会调用主线程的回调方法



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        progressBar = findViewById(R.id.processBar);


        handler = new Handler() {
            @Override
            public void handleMessage(@NonNull Message msg) {
                if (msg.what==0x111){
                    progressBar.setProgress(mProgress);
                }else {
                    Toast.makeText(MainActivity.this, "耗时操作已完成", Toast.LENGTH_SHORT).show();
                    progressBar.setVisibility(View.GONE);

                }

            }
        };


        new Thread(new Runnable() {
            @Override
            public void run() {
                while (true) {
                    mProgress = doWork();
                    Message m = new Message();
                    if (mProgress < 100) {
                        m.what = 0x111;//自定义代码
                        handler.sendMessage(m);
                    } else {

                        m.what = 0x110;
                        handler.sendMessage(m);
                        break;
                    }
                }
            }


            private int doWork() {

                mProgress += Math.random() * 10;
                try {
                    Thread.sleep(200);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                return mProgress;
            }

        }).start();


    }
}